﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Quaack
{
    public partial class Account : System.Web.UI.Page
    {
        // Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            txtGebruikersNaam.Text = userName;

            hidId.Value = GetId(HttpContext.Current.User.Identity.Name).ToString();
        }

        // Interne functies
        public string AvatarLink()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            string avatar;
            string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;
            var query = "SELECT avatarlocation FROM [Quaack].[dbo].[profile] WHERE [username] = " + AddQuotes(userName);

            using (var myConnection = new SqlConnection(connectionString))
            {
                myConnection.Open();

                var myCommand = new SqlCommand(query, myConnection);
                avatar = (string)myCommand.ExecuteScalar();

                myConnection.Close();
                if (String.IsNullOrEmpty(avatar))
                {
                    avatar = "../Content/images/Quaack logo.png";
                }
            }

            return avatar;
        }
        private string AddQuotes(string text)
        {
            return "'" + text + "'";
        }
        private static Guid GetId(string username)
        {
            Guid result = Guid.Empty;
            
            string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;

            var query = "SELECT UserId FROM [Quaack].[dbo].[aspnet_Users] WHERE [UserName] = '" + username + "'";

            using (var myConnection = new SqlConnection(connectionString))
            {
                try
                {
                    myConnection.Open();

                    var myCommand = new SqlCommand(query, myConnection);

                    result = Guid.Parse(myCommand.ExecuteScalar().ToString());

                    myConnection.Close();
                }
                catch
                {
                    result = Guid.Empty;
                }
            }

            return result;
        }
        private void SendMail(String emailAddress, String title, String body)
        {
            MailMessage mail = new MailMessage("quaackwebapp@gmail.com", emailAddress, title, body);
            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com");
            smtp.Credentials = new System.Net.NetworkCredential("quaackwebapp@gmail.com", "quaack2013");
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

        // Events
        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {

        }
        protected void btnWijzig_Click(object sender, EventArgs e)
        {
            var user = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            string userName = HttpContext.Current.User.Identity.Name;
            string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;



            if (user == null)
            {
                lblError.Text = "Gebruiker onbekend";
                return;
            }

            if (Page.IsValid)
            {
                string oudeWachtWoord = txtOudeWachtWoord.Text;
                string nieuwWachtWoord = txtWachtWoord.Text;
                string profielTekst = txtProfielText.Text;
                string email = txtEmail.Text;
                string avatar = txtAvatarLink.Text;
                string mobielNR = txtMobielNR.Text;
                var values = new List<string>();

                if (!String.IsNullOrEmpty(email))
                {
                    user.Email = email;
                    //columns.Add("email");
                    values.Add("email = " + AddQuotes(email));
                }
                if (!String.IsNullOrEmpty(nieuwWachtWoord))
                {
                    user.ChangePassword(oudeWachtWoord, nieuwWachtWoord);
                    //columns.Add("password");
                    values.Add("password = " + AddQuotes(nieuwWachtWoord));
                }

                if (!String.IsNullOrEmpty(profielTekst))
                {
                    //columns.Add("profile");
                    values.Add("profile = " + AddQuotes(profielTekst));
                }

                if (!String.IsNullOrEmpty(avatar))
                {
                    //columns.Add("avatarlocation");
                    values.Add("avatarlocation = " + AddQuotes(avatar));
                }
                if (!String.IsNullOrEmpty(mobielNR))
                {
                    //columns.Add("mobilenumber");
                    values.Add("mobilenumber = " + AddQuotes(mobielNR));
                }

                if (values.Count == 0)
                {
                    lblError.Text = (string)GetLocalResourceObject("ErrorLegeVelden.Text");
                    return;
                }
                // SQL query voor updaten naar de Quaack tabellen
                string updateSql = "UPDATE dbo.profile SET " + string.Join(", ", values.ToArray()) + " WHERE " + "username = " + AddQuotes(userName);
                using (var myConnection = new SqlConnection(connectionString))
                {
                    myConnection.Open();

                    var myCommand = new SqlCommand(updateSql, myConnection);

                    myCommand.ExecuteNonQuery();

                    myConnection.Close();
                }

                Membership.UpdateUser(user);
            }
        }
        protected void btnAnnuleer_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Anoniem/ZoekGebruiker.aspx");
        }
        protected void btnVerwijderProfiel_Click(object sender, EventArgs e)
        {
            if (chkVerwijderAccount.Checked)
            {
                var userId = hidId.Value;
                var name = HttpContext.Current.User.Identity.Name;
                MembershipUser user = Membership.GetUser(name);

                // Gebruiker deactiveren
                if (userId == null)
                {
                    // Geen userId, dan error message
                    lblError.Text = (string)GetLocalResourceObject("VerwijderAccountOnbekend.Text");
                }
                else
                {
                    // Er is een userId
                    try
                    {

                        // Zet veld in de database op geactiveerd
                        user.IsApproved = false;

                        // Zet veld in Quaack tabel op geactiveerd
                        var userName = HttpContext.Current.User.Identity.Name;
                        string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;

                        string updateSql = "UPDATE dbo.profile SET verificationpending = 0 WHERE " + "username = " +  AddQuotes(userName);
                        using (var myConnection = new SqlConnection(connectionString))
                        {
                            myConnection.Open();

                            var myCommand = new SqlCommand(updateSql, myConnection);

                            myCommand.ExecuteNonQuery();

                            myConnection.Close();
                        }

                        // Update gebruikersaccount
                        Membership.UpdateUser(user);

                        // Gebruiker is succesvol gedeactiveerd
                        lblError.Text = (string)GetLocalResourceObject("SuccesAccountVerwijderd.Text");
                        //Response.Redirect("ZoekGebruiker.aspx=", true);
                    }
                    catch
                    {
                        // Error
                        lblError.Text = (string)GetLocalResourceObject("ErrorVerwijderAccountAlgemeen.Text");
                    }
                }

            }
            else
            {
                lblError.Text = (string)GetLocalResourceObject("ErrorChkVerwijderAccount.Text");
            }
        }
        protected void btnVersturen_Click(object sender, EventArgs e)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            string titel = "Uitnodiging voor Quaack";
            string ontvanger = this.tboxEmail.Text;
            string localURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string registratieLink = localURL.Replace("LoggedIn/Account.aspx", "Anoniem/Registreer.aspx");

            StringBuilder uitnodiging = new StringBuilder();
            uitnodiging.Append("U bent uitgenodigd door " + userName + " voor Quaack.");
            uitnodiging.AppendLine();
            uitnodiging.Append("Klik op de volgende link om te registreren: <a href='" + registratieLink + "'>" + registratieLink + "</a>");
            uitnodiging.AppendLine();

            string body = uitnodiging.ToString();

            SendMail(ontvanger, titel, body);

            // Connectiestring uit de web.config
            string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // SQL query voor schrijven naar de Quaack tabellen
                string insertSql =
                    "INSERT INTO dbo.invitation (invitedby, inviteduseremail) VALUES (@invitedby,@inviteduseremail)";

                using (var myConnection = new SqlConnection(connectionString))
                {
                    myConnection.Open();

                    var myCommand = new SqlCommand(insertSql, myConnection);

                    myCommand.Parameters.AddWithValue("@invitedby", userName);
                    myCommand.Parameters.AddWithValue("@inviteduseremail", ontvanger);

                    myCommand.ExecuteNonQuery();

                    myConnection.Close();
                }
            }

            // Verberg de uitnodigen popup
            this.pnlUitnodigen.Visible = false;
        }
        protected void btnUitnodigen_Click(object sender, EventArgs e)
        {
            // Toon de uitnodigen popup
            this.pnlUitnodigen.Visible = true;
        }
        protected void btnAnnuleren_Click(object sender, EventArgs e)
        {
            // Verberg de uitnodigen popup
            this.pnlUitnodigen.Visible = false;
        }
    }
}